package com.logistics.controller.tenant;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.logistics.common.Result;
import com.logistics.entity.SysUser;
import com.logistics.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/tenant/user")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 分页查询用户列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('user:view') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<IPage<SysUser>> getUserList(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer status) {
        IPage<SysUser> result = userService.getUserList(current, size, keyword, status);
        
        // 清空密码字段
        result.getRecords().forEach(user -> user.setPassword(null));
        
        return Result.success(result);
    }
    
    /**
     * 根据ID获取用户信息
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('user:view') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<SysUser> getUserById(@PathVariable Long id) {
        SysUser user = userService.getUserById(id);
        if (user != null) {
            user.setPassword(null); // 清空密码
        }
        return Result.success(user);
    }
    
    /**
     * 创建用户
     */
    @PostMapping
    @PreAuthorize("hasAuthority('user:create') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<SysUser> createUser(@RequestBody SysUser user) {
        // 验证必填字段
        if (user.getUsername() == null || user.getUsername().isEmpty()) {
            return Result.error("用户名不能为空");
        }
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            return Result.error("密码不能为空");
        }
        if (user.getRealName() == null || user.getRealName().isEmpty()) {
            return Result.error("真实姓名不能为空");
        }
        
        SysUser created = userService.createUser(user);
        created.setPassword(null); // 清空密码
        return Result.success(created);
    }
    
    /**
     * 更新用户
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('user:edit') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<Void> updateUser(@PathVariable Long id, @RequestBody SysUser user) {
        user.setId(id);
        userService.updateUser(user);
        return Result.success(null);
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('user:delete') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<Void> deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return Result.success(null);
    }
    
    /**
     * 修改用户状态
     */
    @PutMapping("/{id}/status")
    @PreAuthorize("hasAuthority('user:edit') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<Void> updateStatus(@PathVariable Long id, @RequestBody Map<String, Integer> request) {
        Integer status = request.get("status");
        if (status == null) {
            return Result.error("状态不能为空");
        }
        userService.updateStatus(id, status);
        return Result.success(null);
    }
    
    /**
     * 重置用户密码
     */
    @PutMapping("/{id}/password")
    @PreAuthorize("hasAuthority('user:resetPassword') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<Void> resetPassword(@PathVariable Long id, @RequestBody Map<String, String> request) {
        String newPassword = request.get("newPassword");
        if (newPassword == null || newPassword.isEmpty()) {
            return Result.error("新密码不能为空");
        }
        userService.resetPassword(id, newPassword);
        return Result.success(null);
    }
    
    /**
     * 获取当前用户可创建的角色列表
     */
    @GetMapping("/creatable-roles")
    @PreAuthorize("hasAuthority('user:view') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<Map<String, Object>> getCreatableRoles() {
        return userService.getCreatableRoles();
    }
    
    /**
     * 获取所有具有开票员角色的用户（用于订单筛选）
     */
    @GetMapping("/invoicers")
    @PreAuthorize("hasAuthority('order:view') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<List<SysUser>> getInvoicers() {
        List<SysUser> invoicers = userService.getInvoicers();
        // 清空密码字段
        invoicers.forEach(user -> user.setPassword(null));
        return Result.success(invoicers);
    }
}

